;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.PrePay", [])
        .controller("PrePayCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", function ($scope, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
            // 和后端交互的按钮权限码
            var btnPermissionCode = {
                prePayExport: window.ActionCode.prePayExport,
                prePayReverse: window.ActionCode.prePayReverse,
                prePayAdd: window.ActionCode.prePayAdd
            };
            // 按钮权限
            $scope.btnPermission = {
                prePayExport: true,
                prePayReverse: true,
                prePayAdd: true
            };
            // tab标签展示布尔值
            $scope.activeFlag = [true, false, false];
            // checkbox 选择是否信息
            $scope.markInfo = {
                allChecked: false
            };
            // 分页信息
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            // 高级搜索配置信息
            $scope.toolbarConfig = {};
            // 切换高级搜索展示隐藏
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };
            // 重置搜索条件
            $scope.reset = function () {
                $scope.condition = {};
            };
            // 列表表格配置信息
            $scope.tableConfig = {
                fixedWidth: 150,
                scrollWidth: 1100,
                tableCol: [
                    {
                        name: "客户名称",
                        dataField: "customerName",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "单据类型",
                        dataField: "billTypeStr",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "交易金额",
                        dataField: "transactionAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "总金额",
                        dataField: "totalAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "创建时间",
                        dataField: "createDateStr",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "是否红冲",
                        dataField: "discardFlagStr",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "红冲时间",
                        dataField: "discardDateStr",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "红冲备注",
                        dataField: "discardRemark",
                        width: 160,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "备注",
                        dataField: "remark",
                        width: 160,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "审核状态",
                        dataField: "auditStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 110,
                        isShow: true,
                        isFixed: true
                    }
                ]
            };
            // 设置表格宽度
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };
            // 设置按钮权限
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }
            // 单据类型
            $scope.billTypeList = [
                {value: 0, name: '充值'}, {value: 1, name: '结算'}, {value: 2, name: '退货'}
            ];
            // 列表导出的url和参数
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/prepPay/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/prepPay/exportAll")
            };
            $scope.detailInfo = {};         // 预付款详情信息
            $scope.dataList = [];          // 预付款列表
            $scope.condition = {};         // 搜索条件
            $scope.datePickerFlag = [false, false];
            // 切换时间选择器
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };
            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };
            // 清除客户
            $scope.clearClient = function () {
                $scope.condition.customerId = "";
                $scope.condition.purchaseOrgName = "";
                $scope.search(1);
            };
            // 选择客户
            $scope.selectDealer = function (isSearch) {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    if (isSearch) {
                        $scope.condition.customerId = data.id;
                        $scope.condition.purchaseOrgName = data.companyName;
                        $scope.search(1);
                    } else {
                        $scope.detailInfo.customerId = data.id;
                        $scope.detailInfo.customerName = data.companyName;
                    }
                })
            };
            // 切换标签页
            $scope.changeTab = function (index) {
                if (index === 0) {
                    // 进入结算卡列表页，初始化预付款详情信息
                    $scope.detailInfo = {};
                }
                angular.forEach($scope.activeFlag, function (activeFlag) {
                    activeFlag = false;
                });
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
            };
            // 选择所有列
            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };
            // 选择一列
            $scope.selectSingle = function (item) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll($scope.dataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };
            // 检查是否全部已选
            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }
            // 获取已选择的预收款id  导出要用
            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }
            // 取消
            $scope.cancel = function () {
                $scope.changeTab(0);
            };
            // 新增预付款
            $scope.addPrePay = function () {
                $scope.detailInfo.paymentDate = new Date();
                $scope.detailInfo.settleType = "预付款";
                $scope.changeTab(1);
            };
            // 保存预付款
            $scope.saveData = function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var url = '/prepPay/add';
                var param = angular.extend($scope.detailInfo, {billType: 0});
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                });
            };
            $scope.goDiscard = function (item) {
                $scope.changeTab(2);
                $scope.detailInfo.id = item.id;
            };
            // 作废预付款
            $scope.confirmDiscard = function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var url = '/prepPay/discard';
                var params = angular.copy($scope.detailInfo);
                ybWidget.ShowMessage("确定要红冲吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post('device', url, params).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        $scope.search();
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.changeTab(0);
                    })
                });
            };

            $scope.search = function (curPage) {
                $scope.markInfo.allChecked = false;
                if (curPage) $scope.pageInfo.CurPage = curPage;
                getPrepPayList();
            };

            // 获取预付款列表
            function getPrepPayList () {
                var url = '/prepPay/list';
                //遍历搜索条件对象里的空值并删除  不然搜索不出数据
                Object.keys($scope.condition).forEach(function (key) {
                    if ($scope.condition[key]!==0) {
                        if (!$scope.condition[key]) delete $scope.condition[key];
                    }
                });
                var filters = angular.copy($scope.condition);
                filters.queryPageFlag = true;
                var params = {
                    filters: filters,
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage
                };
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(res.value.list, function (item) {
                        item.isChecked = false;
                        item.billTypeStr = $filter('PrepPayBillType')(item.billType);
                        item.createDateStr = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.discardDateStr = $filter("YbDate")(item.discardDate, 'yyyy-MM-dd HH:mm:ss');
                        item.discardFlagStr = $filter('TrueOrFalse')(item.discardFlag, 'normal');
                        item.auditStatusShow = $filter("ProgressStatus")(item.auditStatus, "auditStatus");
                    });
                    $scope.pageInfo.totalRows = res.value.total;
                    $scope.pageInfo.totalPages = res.value.pages;
                    $scope.dataList = res.value.list;
                })
            }

            $scope.isReverseList = [
                {id: 0, name: "否"},
                {id: 1, name: "是"}
            ];
            $scope.auditStatusList = [
                {id: 0, name: "待审核"},
                {id: 1, name: "审核通过"}
            ];

            // 付款方式
            $scope.payTypeList = [
                {id: 1, name: "现金"},
                {id: 2, name: "差价"},
                {id: 3, name: "承兑"},
                {id: 4, name: "融资"},
                {id: 5, name: "调账"},
                {id: 6, name: "返利"},
                {id: 7, name: "服务费"},
                {id: 8, name: "报告抵扣"},
                {id: 9, name: "易贷"},
                {id: 10, name: "三方转账"},
                {id: 11, name: "电汇"},
                {id: 12, name: "其它"},
            ];

            $scope.go2checkData = function(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    $scope.detailInfo.paymentDateF = $filter("YbDate")(data.paymentDate, "yyyy-MM-dd");
                    $scope.detailInfo.payTypeF = $filter("PayTypeF")(data.payType);
                    $scope.changeTab(3);
                })
            };

            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/prepPay/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.checkData = function (id) {
                ybWidget.ShowMessage("确定要通过吗？", MESG_TYPE.Ask).then(function () {
                    var param = {
                        id: id
                    };
                    ybHttp.Get('device', '/prepPay/audit', param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return false;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search();
                        $scope.changeTab(0);
                    });
                });
            };

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "PrePay"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 初始化页面信息
            (function () {
                getPrepPayList();
                UserContextService.SetBtnPermission(setBtnPermission);
                $scope.setFixedWidth();
            })()
        }])
    ;
})(window, window.angular);